package com.hy.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.hy.model.User;
import com.hy.service.IUserService;

@Controller
@RequestMapping("/user")
public class UserController {
    private IUserService userService;

    @Autowired
    public void setUserService(IUserService userService) {
        this.userService = userService;
    }

    @RequestMapping("/home")
    public ModelAndView home() {
        ModelAndView mav = new ModelAndView("index");
        return mav;
    }

    @RequestMapping(method = RequestMethod.POST, path = "/login")
    public ModelAndView login(HttpServletRequest request, String loginname,
                              String password) {
        User user = userService.login(loginname, password);
        if (user != null) {
            request.getSession().setAttribute("userinfo", user);
            ModelAndView mav = new ModelAndView("home");//主界面
            return mav;
        } else {
            ModelAndView mav = new ModelAndView("error");
            mav.addObject("msg", "登录失败");
            return mav;
        }
    }

    @RequestMapping(method = RequestMethod.POST, path = "/add")
    public ModelAndView add(User user) {
        user = userService.add(user);
        if (user != null&&user.getId()!=null) {
            ModelAndView mav = new ModelAndView("index");
            return mav;
        } else {
            ModelAndView mav = new ModelAndView("error");
            mav.addObject("msg", "用户名已存在，请重新注册");
            return mav;
        }
    }

    @RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, path = "/checkSameLoginname")
    @ResponseBody
    public String checkSameLoginname(String loginname) {
        Map<String, Boolean> resultMap = new HashMap<String, Boolean>();
        resultMap.put("valid", userService.checkSameLoginname(loginname));
        return JSON.toJSONString(resultMap);
    }
}